const koa = require("koa")
const router = require("koa-router")();
const app = new koa();
const cheerio = require("cheerio");
const puppeteer = require("puppeteer")

router.get("/",async ctx =>{
    const browser = await puppeteer.launch({
        // headless:false,
        defaultViewport:null
    })
    const page = await browser.newPage();
    await page.goto("https://movie.douban.com/top250")
    var content  =  await page.content();
	var $ = cheerio.load(content,{
        decodeEntities:false
    })
    var result = [];
    var items = $(".grid_view .item");
    items.each((index,value)=>{
        var imgUrl = $(value).find(".pic img").attr("src");
        var title = $(value).find(".pic img").attr("alt")
        var labels = $(value).find(".bd p").html().trim().split("<br>")[1].trim().split("/").map(item=>item.trim())
        var rating_num = $(value).find(".star .rating_num").html()
        var evaluate = $(value).find(".star span:last-child").html().replace(/[^\d]/g,"")
        var slogo = $(value).find(".quote .inq").html()
        result.push({
            imgUrl,
            title,
            labels,
            rating_num,
            evaluate,
            slogo
        })
    })
    ctx.body = result;
})

router.get("/subject/:id",async ctx=>{
    const browser = await puppeteer.launch({
        // headless:false,
        defaultViewport:null
    })
    const page = await browser.newPage();
    await page.goto(`https://movie.douban.com/subject/1292052/`);
    const content = await page.content();
    var $ = cheerio.load(content,{
        decodeEntities:false
    })
    var arr={};
    var movieClass=[];
    var actor=[];
    let item = $("#content h1 span").html().split(" ")[0];
    let img = $(".nbgnbg img").attr("src");
    let short = $(".short span").text();
    let top250No = $(".top250-no").html();
    $("#info span[property='v:genre']").each((index,res)=>{
        movieClass.push($(res).html());
    })
    let showTime =$("#info span[property='v:initialReleaseDate']").html()
    let longTime =$("#info span[property='v:runtime']").html()
    let rating_num = $(".rating_num").html()
    let movieClassStr = movieClass.join("/");
    let EnglishName = $(".nbgnbg img").attr("alt");
    let rating_people = $(".rating_people span").html()
    $(".celebrity").each((index,res)=>{
        let actorImg = $(res).find(".avatar").attr("style");
        let name = $(res).find(".info .name .name").html();
        let role = $(res).find(".info .role").html();
        actorImg = actorImg.match(/[^\(\)]+(?=\))/g)[0];
        // console.log(actorImg);
        actor.push({
            actorImg,
            name,
            role
        })
    })
    Object.assign(arr,{
        item,EnglishName,img,short,top250No,
        movieClassStr,showTime,
        longTime,rating_num,rating_people,actor
    })
    ctx.body = arr;
})
app.use(router.routes());
app.listen(8081)